<?php
namespace My\Controller;

use Utuo\BackgroundController;
use My\Model\WechatUserModel;

class DealerController extends BackgroundController {
	
	public $belong = array(
		'0' => '总商家',
		//'不定' => '已指定代理',
	);
	
	protected function _initialize() {
		$this->setControllerTitle('金牌会员管理');
		$this->setActionTitle(array(
				'index' => '金牌会员管理',
		        'add' => '添加金牌会员',
				'modify' => '修改金牌会员',
				'recycle' => '回收站' ,
		));
		$this->setActionNav(array(
				/*'index',
				'recycle'*/
		));
		$this->setLinkNav("金牌会员列表", U('DistributionShopWechatUser/index', array('type' => WechatUserModel::USER_TYPE_FRANCHISED_DEALER)));
		$this->setLinkNav("金牌会员申请列表", U('DealerApply/index'));
	}
	
	public function indexAction() {
		$this->display();
	}
	
	/**
	 * 添加金牌会员信息
	 */
	public function addAction() {
		$applyId = I("applyId", 0, "intval");
		$dealerId = I('wechat_uid', 0, "intval");
		$wechatUser = M("WechatUser")->where("cid=%d and id=%d", $this->aid, $dealerId)->find();
		if ( $wechatUser ) {
			$dealer['wechat_uid'] = $dealerId;
			$this->assign("dealer", $dealer);
			$this->display("save");
		} else {
			exit('请先选择已绑定此平台的微信用户');
		}
	}
	
	/**
	 * 修改金牌会员信息
	 */
	public function modifyAction() {
	    $model = CONTROLLER_NAME;
	    $agent = D($model)->getOneById();
	    $this->assign(lcfirst($model), $agent);
	    $this->display("save");
	}
	
	/**
	 * 提交修改
	 * @see \Utuo\BackgroundController::submitPost()
	 */
	public function submitPost( $model ) {
		$model = is_object($model) ? $model : D($model);
		if ($model->isCreated or $model->create()) {
			if (empty($_REQUEST['id'])) {
				unset($model->id);
				$id = $model->add();
				if ( $id ) {
					$this->ajaxSuccess("添加成功！", array('id'=>$id));
				} else {
					$this->ajaxError("添加失败！");
				}
			} else {
				if (false !== $model->save()) {
					$this->ajaxSuccess("修改成功！");
				} else {
					$this->ajaxError("修改失败！");
				}
			}
		} else {
			$this->ajaxError($model->getError());
		}
	}
	
}